/**
 * util.js
 * general utility functions
 */
//function getDistance(score, maxValue){
//	var dist = 20*maxDistance*maxValue / ((maxDistance-20)*score + 20*maxValue);
//	return dist;
//}

function loading(msg){
	$('#loading-box').show();
	$('#message-box').html((msg) ? msg : "Fetching data...");
}	

function loaded(){
	$('#loading-box').hide();
	$('#message-box').empty();
}

function convertFBTimestamp(timestamp){
	var d = new Date();
	d.setTime(timestamp +  '000');
	return d;
}

//convert flag to upper datatype like message, post, comment, like
//function convertFlagToUpperDataType(flag){
//	var upperDataTypes = ["message", "post", "comment", "like"];
//	var returnVal = null;
//	for(var i = 0; i < upperDataTypes.length; i++){
//		if(flag.toLowerCase().indexOf(upperDataTypes[i]) > -1){
//			returnVal = upperDataTypes[i];
//			break;
//		}
//	}
//	return returnVal;
//}

//call XHR
function callXHR(mode, callbackFn){
	
	//increase current number of fetching process
	currentNumberOfFetch++;
	
	var jqxhr = $.getJSON(app_dir+'/ajax/getFriendsDataAJAX.php?mode='+mode, null, function(response){
		//reduce current number of fetching process
		currentNumberOfFetch--;
		if(callbackFn != null && callbackFn != undefined){
			callbackFn.call(this, response);
		}
	})
	.error(function(){
		//reduce current number of fetching process
		currentNumberOfFetch--;
		//send error object to callback
		callbackFn.call(this, {"error":"callXHR error"})
	})
	.complete(function(){
		
	});
}

//a function that return a number of member variable of an object
//eg)var length = Object.size(anArray);
Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// concatenate two result data array
function concat(data1, data2) {

	// variables
	var mode1, mode2, error1, error2;
	
	// copy first object
	var data = jQuery.extend(true, {}, data1);

	try {

		// calculate mode
		mode1 = data1.mode;
		mode2 = data2.mode;
		
		
		if (data1.error != undefined) {
			error1 = data1.error;
		}else{
			error1 = 0;
		}


		if (data2.error != undefined) {
			error2 = data2.error;
		}else{
			error2 = 0;
		}
		
		// concatenate data
		// traverse second array and add stuffs
		// check if data2 is a avalid object
		if (data2.data != undefined && typeof data2.data === 'object') {
			
			// calculate modes
			data.mode = mode1 | mode2;
			
			// calculate error
			var success1 = mode1 & (~error1);
			var success2 = mode2 & (~error2);
			data.error = error1 & (~success2) | error2 & (~success1);
			
			//check if there is data
			if (Object.size(data2.data) > 0) {
				for ( var id in data2.data) {
					// if it's new, just add otherwise concat
					if (data.data[id] == undefined) {
						// add
						data.data[id] = data2.data[id];
					} else {
						// concat
						for ( var flag in data2.data[id]) {
							if (data.data[id][flag] != undefined) {
								// DUPLICATION ERROR: ignore second array values
							} else {
								// add flag value
								data.data[id][flag] = data2.data[id][flag];
							}
						}//inside loop for datatypes
					}//if
				}//outside loop for friends
			}//check if data is not null
		}//if if object is valid
	} catch (err) {
		trace2(err);
	}

	return data;
}

/*
 * Functions for debugging
 */
function trace(msg){
	if(global.debug && this.console && typeof this.console.log != "undefined"){
		console.log(msg);
	}
}

function trace2(msg){
	if(global.debug){
		try{
			console.log(msg);
		}catch(e){}
	}
}

//get an upper datatype from flag like message, post, comment, like
function getTypeByFlag(flag){
	//check if parameter is not null and undefined
	if(flag != undefined){
		var type;
		for(var i = 0; i < upperDataTypes.length; i++){
			if(flag.toLowerCase().indexOf(upperDataTypes[i]) > -1){
                type = upperDataTypes[i];
                break;
			}
		}
	}
    return type;
}

function getFlagByFlagMode(flagMode){
	var retFlag;
	//check flags is not null and not undefined AND parameter is neither null or undefined as well
	if(flags != undefined && flagMode != undefined){
		//looping
		for(var flag in flags){
			//check if they are same
			if(flags[flag] == flagMode){
				retFlag = flag; 
			}
		}
	}
	//if there is no match return null
	return retFlag;
}

function getTypeByFlagMode(flagMode){
	//check input parameter is not null and not undefined
	if(flagMode != undefined){
		var flag, type;
		flag = getFlagByFlagMode(flagMode);
		if(flag != undefined){
			type = getTypeByFlag(flag);
		}
	}
	return type;
}

//from http://en.wikipedia.org/wiki/Queue_(data_structure)
function Queue() {
  var data = [];

  this.isEmpty = function() {
      return (data.length == 0);
  };

  this.enqueue = function(obj) {
      data.push(obj);
  };

  this.dequeue = function() {
      return data.shift();
  };

  this.peek = function() {
      return data[0];
  };

  this.size = function(){
	  return data.length;
  };
  
  this.clear = function() {
      data = [];
  };
}

function getQueryString(){
    return window.location.search.substring(1);
}

/*
 * Convert rgb to hex 
 */
var hexDigits = new Array
("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
}

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}
